package com.heima.user.filter;

import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author mrchen
 * @date 2022/1/6 9:26
 */
@WebFilter(filterName = "appTokenFilter",urlPatterns = "/*")
@Component
@Slf4j
public class AppTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取请求头中的 userId
       HttpServletRequest request = (HttpServletRequest)servletRequest;
        String userId = request.getHeader("userId");
        // 2. 如果userId不等于空 + 并且不等于 0
        if(StringUtils.isNotBlank(userId)&&Integer.valueOf(userId)!=0){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            //     存入ThreadLocal中
            AppThreadLocalUtils.setUser(apUser);
        }
        // 3. 放行请求
        filterChain.doFilter(servletRequest,servletResponse);
        // 4. 清空用户信息
        AppThreadLocalUtils.clear();
    }
}